package com.wildwolf.project.wildwolf.ui.register;

import java.io.File;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.UUID;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.preference.PreferenceManager;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.wildwolf.project.wildwolf.R;
import com.wildwolf.project.wildwolf.WildWolfApplication;
import com.wildwolf.project.wildwolf.config.AppConfig;
import com.wildwolf.project.wildwolf.ui.Login;
import com.wildwolf.project.wildwolf.utils.HttpAPI;
import com.wildwolf.project.wildwolf.utils.LogTagUtil;

/**
 * 头像设置
 * 
 * @author LEON
 * 
 */
public class AvatarActivity extends Activity implements View.OnClickListener {
	private static final String TAG = LogTagUtil
			.getLogTag(AvatarActivity.class);
	/**
	 * 返回上一个界面
	 */
	private TextView prev = null;
	/**
	 * 完成注册过程
	 */
	private TextView next = null;
	/**
	 * 选择头像
	 */
	private TextView chooseAvatar = null;
	/**
	 * 裁剪照片的文件
	 */
	private String tailorPhotoUrl = "";
	/**
	 * 显示裁剪后的头像
	 */
	private ImageView avatar = null;

	private Intent intent = null;
	/*
	 * 
	 */
	private static  ProgressDialog registerProgressDialog = null;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.layout_reg_avatar);
		intent = getIntent();
		prev = (TextView) findViewById(R.id.textView_avatar_Prev);
		next = (TextView) findViewById(R.id.textView_Avatar_Next);
		chooseAvatar = (TextView) findViewById(R.id.textView_choose_avatar);
		avatar = (ImageView) findViewById(R.id.imageView_avatar);

		prev.setOnClickListener(this);
		next.setOnClickListener(this);
		chooseAvatar.setOnClickListener(this);

	}

	@Override
	public void onClick(View v) {
		if (v == prev) {
			finish();
		} else if (v == next) {
			registerProgressDialog = new ProgressDialog(this,
					ProgressDialog.STYLE_HORIZONTAL);
			registerProgressDialog.setIcon(R.drawable.progress);
			ProgressDialog.show(this,AvatarActivity.this.getString(R.string.activity_label_reg_account) , AvatarActivity.this.getResources().getStringArray(R.array.register_progress_state)[0]);
			new RegisterAsyncTask().execute(intent);
			Toast.makeText(
					this,
					intent.getCharSequenceExtra(AppConfig.REGISTERKEY.ENCOUNTER_REGISTER_ACCOUNTNAME),
					Toast.LENGTH_SHORT).show();
		} else {
			Builder chooseAlert = new AlertDialog.Builder(this);
			// 设置标题
			chooseAlert.setTitle(R.string.activity_label_reg_avatar);
			// 设置手机选取照片事件监听
			chooseAlert.setNegativeButton(R.string.dialog_avatae_fileManager,
					new DialogInterface.OnClickListener() {
						@Override
						public void onClick(DialogInterface dialog, int which) {
							dialog.dismiss();
							Intent intent = new Intent(Intent.ACTION_PICK);
							intent.setDataAndType(
									MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
									AppConfig.FILETYPE.IMAGE);
							startActivityForResult(intent,
									AppConfig.RESULT_CODE.CHOOSE_FILE);
						}
					});
			// 设置手机拍照事件监听
			chooseAlert.setPositiveButton(R.string.dialog_avatae_takePhoto,
					new DialogInterface.OnClickListener() {
						@Override
						public void onClick(DialogInterface dialog, int which) {
							dialog.dismiss();
							Intent intent = new Intent(
									MediaStore.ACTION_IMAGE_CAPTURE);
							tailorPhotoUrl = UUID.randomUUID().toString();
							intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri
									.fromFile(new File(Environment
											.getExternalStorageDirectory(),
											tailorPhotoUrl
													+ AppConfig.IMAGE.PNG)));
							startActivityForResult(intent,
									AppConfig.RESULT_CODE.TAKE_PHOTO);
						}
					});
			chooseAlert.show();
		}

	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (resultCode == AppConfig.RESULT_CODE.NONE) {
			return;
		}
		if (AppConfig.RESULT_CODE.CHOOSE_FILE == requestCode) {
			clippingAvatar(data.getData());
		} else if (AppConfig.RESULT_CODE.TAKE_PHOTO == requestCode) {
			clippingAvatar(data.getData());

		} else if (AppConfig.RESULT_CODE.TAIL_PHOTO == requestCode) {
			avatar.setImageBitmap((Bitmap) data.getParcelableExtra("data"));
		}

		super.onActivityResult(requestCode, resultCode, data);
	}

	/**
	 * 图像裁剪
	 * 
	 * @param uri
	 */
	private void clippingAvatar(Uri uri) {
		Intent intent = new Intent("com.android.camera.action.CROP");
		intent.setDataAndType(uri, AppConfig.FILETYPE.IMAGE);
		intent.putExtra("crop", "true");
		intent.putExtra("aspectX", 1);
		intent.putExtra("aspectY", 1);
		intent.putExtra("outputX", 150);
		intent.putExtra("outputY", 150);
		intent.putExtra("return-data", true);
		startActivityForResult(intent, AppConfig.RESULT_CODE.TAIL_PHOTO);
	}
	 /**
     * 存储账户信息到设置里面
     */
    private void configureAccount(String accountName,String password) {
	SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(this);
	SharedPreferences.Editor edit = settings.edit();
	edit.putString(WildWolfApplication.ACCOUNT_USERNAME_KEY, accountName);
	edit.putString(WildWolfApplication.ACCOUNT_PASSWORD_KEY, password);
	edit.commit();
    }
	@SuppressWarnings("rawtypes")
	private class RegisterAsyncTask extends AsyncTask<Intent, Integer, HashMap> {
		/**
		 * 错误信息
		 */
		private String errorMessage;
		/**
		 * 收集用户注册信息
		 */
		public static final int STATE_REGISTER_COLLECT = 0;
		/**
		 * 正在连接.
		 */
		public static final int STATE_CONNECTION_RUNNING = 1;
		/**
		 * 连接成功，正在注册
		 */
		public static final int STATE_REGISTER_RUNNING = 2;
		/**
		 * 注册成功
		 */
		public static final int STATE_REGISTER_SUCCESS = 3;
		/**
		 * 注册失败
		 */
		public static final int STATE_REGISTER_FAILED = 4;
		private Intent valuePairIntent = null;
		@SuppressWarnings("unchecked")
		@Override
		protected HashMap doInBackground(Intent... intent) {
			String reponseJSON = null;
			HashMap<String, String> jsonMap = null;
			 valuePairIntent = intent[0];
			publishProgress(STATE_REGISTER_COLLECT);
			List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
			nameValuePairs.add(new BasicNameValuePair("secretkey",
					AppConfig.ENCOUNTER_SECRET_KEY.trim()));
			nameValuePairs.add(new BasicNameValuePair("email", ""));
			nameValuePairs
					.add(new BasicNameValuePair(
							"plainPassword",
							valuePairIntent
									.getCharSequenceExtra(
											AppConfig.REGISTERKEY.ENCOUNTER_REGISTER_PASSWORD)
									.toString().trim()));
			nameValuePairs
					.add(new BasicNameValuePair(
							"userName",
							valuePairIntent
									.getCharSequenceExtra(
											AppConfig.REGISTERKEY.ENCOUNTER_REGISTER_ACCOUNTNAME)
									.toString().trim()));
			nameValuePairs
					.add(new BasicNameValuePair(
							"accountName",
							valuePairIntent
									.getCharSequenceExtra(
											AppConfig.REGISTERKEY.ENCOUNTER_REGISTER_USERNAME)
									.toString().trim()));
			nameValuePairs.add(new BasicNameValuePair("gender", valuePairIntent
					.getCharSequenceExtra(
							AppConfig.REGISTERKEY.ENCOUNTER_REGISTER_GENDER)
					.toString().trim()));
			try {
				nameValuePairs
						.add(new BasicNameValuePair(
								"birthday",
								String.valueOf(new SimpleDateFormat(
										"yyyy-MM-dd")
										.parse(valuePairIntent
												.getCharSequenceExtra(
														AppConfig.REGISTERKEY.ENCOUNTER_REGISTER_BIRTHDAY)
												.toString().trim()).getTime())));
			} catch (ParseException e) {
			}
			nameValuePairs.add(new BasicNameValuePair("friendsPurpose",
					"人生中最大的风险是过没有任何风险的生活。"));
			nameValuePairs.add(new BasicNameValuePair("height", String
					.valueOf(170)));
			nameValuePairs.add(new BasicNameValuePair("weight", String
					.valueOf(60)));
			nameValuePairs.add(new BasicNameValuePair("constellation", "0"));
			nameValuePairs.add(new BasicNameValuePair("favour", "0"));
			nameValuePairs.add(new BasicNameValuePair("interestValueMap", ""));
			nameValuePairs.add(new BasicNameValuePair("introduction",	"人生中最大的风险是过没有任何风险的生活。"));
			publishProgress(STATE_CONNECTION_RUNNING);
			try {
				publishProgress(STATE_REGISTER_RUNNING);
				reponseJSON = HttpAPI.post(AppConfig.ENCOUNTER_SERVLET_API,
						nameValuePairs);
				jsonMap = com.alibaba.fastjson.JSON.parseObject(reponseJSON,HashMap.class);
				publishProgress(STATE_REGISTER_SUCCESS);
			} catch (Exception e) {
				publishProgress(STATE_REGISTER_FAILED);
				Log.e(TAG, e.getMessage(), e);
				errorMessage = e.getMessage();
			}
			return jsonMap;
		}

		@Override
		protected void onCancelled() {
			super.onCancelled();
		}

		@Override
		protected void onPostExecute(HashMap resultJson) {
			super.onPostExecute(resultJson);
			if(resultJson!=null){
				int  key =Integer.valueOf(resultJson.get(AppConfig.SERLVERT_REPONSE.ENCOUNTER_REPONSE_CODE_KEY).toString());
				switch (key) {
				case AppConfig.SERLVERT_REPONSE.ENCOUNTER_UNKNOWN_ERROR:

					break;
				case AppConfig.SERLVERT_REPONSE.ENCOUNTER_REQUEST_METHOD_ERROR:

					break;
				case AppConfig.SERLVERT_REPONSE.ENCOUNTER_REQUEST_DENY_ACCESS:

					break;
				case AppConfig.SERLVERT_REPONSE.ENCOUNTER_USERNAME_EXISTS:

					break;
				case AppConfig.SERLVERT_REPONSE.ENCOUNTER_USER_REGISTRATION_FAILED:

					break;
				case AppConfig.SERLVERT_REPONSE.ENCOUNTER_USER_REGISTRATION_SUCCESS:
						configureAccount(valuePairIntent.getCharSequenceExtra(AppConfig.REGISTERKEY.ENCOUNTER_REGISTER_ACCOUNTNAME).toString(),valuePairIntent.getCharSequenceExtra(AppConfig.REGISTERKEY.ENCOUNTER_REGISTER_PASSWORD).toString());
					break;
				default:
					break;
				}
				Intent i = new  Intent(AvatarActivity.this,Login.class);
				startActivity(i);
				finish();
		finish();
			}else{
				Toast.makeText(AvatarActivity.this, getErrorMessage(), Toast.LENGTH_SHORT).show();
				registerProgressDialog.dismiss();
			}
		}

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
		}

		@Override
		protected void onProgressUpdate(Integer... values) {
			System.out.print(getResources().getStringArray(R.array.register_progress_state)[values[0]]);
			registerProgressDialog.dismiss();
			registerProgressDialog.setMessage(getResources().getStringArray(R.array.register_progress_state)[values[0]]);
			
		}
		/**
		 * 返回错误信息
		 * 
		 * @param errorMessage
		 *            NULL表示没有错误信息
		 */
		public String getErrorMessage() {
			return  errorMessage;
		}

	}

}
